use crypto::digest::Digest;
use hex::encode;
use rand::random;

/// ## hash_password
/// 标准的hash_password实现
/// 由于结果使用了`copy_from_slice`所以需要提前分配好长度
pub fn hash_password<D: Digest>(password: &str, slat: &str, output: &mut [u8]) {
    let mut hasher = D::new();
    hasher.update(password.as_bytes());
    hasher.update(b"#");
    hasher.update(slat.as_bytes());
    output.copy_from_slice(hasher.finalize().as_slice())
}

/// ## random_string
/// 使用浮点随机数直接生成随机字符串
pub fn random_string() -> String {
    let rand_float: f64 = random();
    encode(rand_float.to_string()[2..].as_bytes())
}

/// ## jssdk_signature
/// 用于JSSDK的签名
/// [具体算法](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#%E9%99%84%E5%BD%951-JS-SDK%E4%BD%BF%E7%94%A8%E6%9D%83%E9%99%90%E7%AD%BE%E5%90%8D%E7%AE%97%E6%B3%95)
pub fn jssdk_signature(noncestr: &str, jsapi_ticket: &str, timestamp: i64, url: &str) -> String {
    use sha1::Sha1;
    let mut d = Sha1::new();
    // jsapi_ticket= & noncestr= & timestamp= & url=
    d.update("jsapi_ticket=");
    d.update(jsapi_ticket);
    d.update("&");
    d.update("noncestr=");
    d.update(noncestr);
    d.update("&");
    d.update("timestamp=");
    d.update(timestamp.to_string().as_str());
    d.update("&");
    d.update("url=");
    d.update(url);
    let s = d.finalize().as_slice().to_vec();
    String::from_utf8(s).unwrap_or_default()
}
